import turtle as tl
import numpy as np

"""
Ref:
    The Beauty of Bézier Curves https://www.youtube.com/watch?v=aVwxzDHniEw
"""

P = np.array([[-200, -200], [-240, 240], [260, 230], [260, -220]])


def draw_points():
    # draw point
    tl.color("red")
    for p in P:
        tl.penup()
        tl.goto(p[0], p[1])
        tl.pendown()
        tl.dot(16)

    # draw lines
    tl.color("black")
    tl.penup()
    for p in P:
        tl.goto(p[0], p[1])
        tl.pendown()

def draw_point(p, ps=12, cl='blue'):
    tl.color(cl)
    tl.penup()
    tl.goto(p[0], p[1])
    tl.pendown()
    tl.dot(ps)

def draw_line(p1, p2, cl='black'):
    tl.color(cl)
    tl.penup()
    tl.goto(p1[0], p1[1])
    tl.pendown()
    tl.goto(p2[0], p2[1])


def draw():
    tl.hideturtle()

    tl.speed(0)
    tl.tracer(1, 1)

    bc = tl.Turtle()
    bc.hideturtle()
    bc.penup()
    bc.goto(P[0][0], P[0][1])
    bc.pendown()

    # draw point A, B, C, D
    nseg = 400
    for t_ in range(nseg+1):
        t = t_ / nseg

        tl.reset()
        draw_points()

        A = P[0]*(1-t) + P[1]*t
        B = P[1]*(1-t) + P[2]*t
        C = P[2]*(1-t) + P[3]*t
        D = A*(1-t) + B*t
        E = B*(1-t) + C*t
        F = D*(1-t) + E*t

        draw_point(A)
        draw_point(B)
        draw_point(C)
        draw_point(D)
        draw_point(E)
        draw_point(F)

        draw_line(A, B)
        draw_line(B, C)
        draw_line(D, E)

        bc.goto(F[0], F[1])


if __name__ == "__main__":
    draw()

    tl.mainloop()
